<template>
  <div class="user-payment">
    <div class="tTable"
      v-if="!isFirstLoad"
      style="overflow-x: auto;"
      v-loading="loading && !isFirstLoad">
      <table style="width: 100%; min-width: 780px;"
        v-if="tableData && tableData.length>0">
        <thead>
          <tr>
            <th style="width: 5%">
              <div class="cell">
                #
              </div>
            </th>
            <th style="width: 18%">
              <div class="cell">
                {{$t('user_id')}}
              </div>
            </th>
            <th style="width: 15%">
              <div class="cell">
                {{$t('user_type')}}
              </div>
            </th>
            <th style="width: 15%">
              <div class="cell">
                {{$t('user_fee')}}
              </div>
            </th>
            <th style="width: 12%">
              <div class="cell">
                {{$t('user_status')}}
              </div>
            </th>
            <th style="width: 15%">
              <div class="cell">
                {{$t('user_time')}}
              </div>
            </th>
            <th style="width: 20%">
              <div class="cell">
                {{$t('user_invoice')}}
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr class="el-table__row"
            v-for="(row, key) in tableData"
            :key="key">
            <td>
              <div class="cell">
                <p class="text-base text-gray-1000 break-words">
                  {{key+1}}
                </p>
              </div>
            </td>
            <td>
              <div class="cell">
                <p class="text-base text-gray-1000 break-words"
                  v-if="hasRealVal(row.order_sn)">
                  {{ row.order_sn }}
                </p>
              </div>
            </td>
            <td>
              <div class="cell">
                <p class="text-base font-semibold text-gray-1000 break-words">
                  {{getOrderType(row.type)}}
                </p>
              </div>
            </td>
            <td>
              <div class="cell">
                <p class="text-base text-gray-1000 break-words"
                  v-if="hasRealVal(row.paid_amount)">
                  $ {{ row.paid_amount }}
                </p>
              </div>
            </td>
            <td>
              <div class="cell fs-0">
                <span class="statu"
                  v-if="row.order_status"
                  :class="{'order-statu-unpaid': row.order_status === 1, 'order-statu-paid': row.order_status === 2, 'order-statu-refunded': row.order_status === 3 }">
                  {{ $t(orderStatusOptions[row.order_status - 1].label) }}
                </span>
              </div>
            </td>
            <td>
              <div class="cell">
                <p class="text-base text-gray-1000 break-words"
                  v-if="hasRealVal(row.paid_at)">
                  {{ $formattedDate(row.paid_at, fI18n, locale, true)}} UTC
                </p>
              </div>
            </td>
            <td>
              <div class="cell">
                <el-button type="primary"
                  class="btn"
                  @click="downloadInvoice(row.order_sn)"
                  :loading="downloadOrderSn && downloadOrderSn === row.order_sn"
                  :disabled="hasRealVal(downloadOrderSn)"
                  v-if="hasRealVal(row.order_status) && row.order_status !== 1">{{ $t("user_downloadInvoice") }}</el-button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <el-empty v-else
        class="sm:flex-1"
        :description="$t('user_noData')"></el-empty>
    </div>

    <div class="tTable skeleton"
      v-else
      style="overflow-x: auto;">
      <el-skeleton animated>
        <template slot="template">
          <table style="width: 100%; min-width: 780px;">
            <thead>
              <tr>
                <th style="width: 5%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 18%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 15%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 15%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 12%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 15%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
                <th style="width: 20%">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </th>
              </tr>
            </thead>
            <tbody>
              <tr class="el-table__row"
                v-for="(row, key) in 5"
                :key="key">
                <td v-for="(row, key) in 7"
                  :key="`td-${key}`">
                  <div class="cell">
                    <el-skeleton-item variant="div" />
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </template>
      </el-skeleton>
    </div>
    <div class="pagination"
      v-if="pagination.total && pagination.total > pagination.pageSize">
      <el-pagination :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        :layout="_isMobile() ? minLayout : layout"
        :small="_isMobile() ? true : false"
        :total="pagination.total"
        :disabled="loading"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <download-invoice ref="downloadInvoice"
      :pageData="downloadData"
      :userData="downloadUserData"></download-invoice>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'UserPayment',
  props: {},
  data() {
    return {
      loading: false,
      isFirstLoad: true,
      tableData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      layout: 'total, sizes, prev, pager, next, jumper',
      minLayout: 'prev, next',

      orderStatusOptions: [
        {
          label: 'user_statuUnpaid',
          value: 1,
          class: 'order-statu-unpaid',
        },
        {
          label: 'user_statuPaid',
          value: 2,
          class: 'order-statu-paid',
        },
        {
          label: 'user_statuRefunded',
          value: 3,
          class: 'order-statu-refunded',
        },
      ],

      downloadOrderSn: null,

      downloadData: {},
      downloadUserData: {},
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  created() {
    this.getList({
      per_page: 10,
      page: 1,
    })
  },
  methods: {
    async getList(page) {
      let req = JSON.parse(JSON.stringify({ ...page }))
      try {
        /* 搜索条件固化 */
        for (let item in req) {
          if (req[item] === null || req[item] === '') {
            delete req[item]
          }
        }

        /* if (this.$route.name === 'user' || this.$route.name === 'lang-user') {
          this.$router
            .replace({
              query: { ...req },
            })
            .catch(() => {})
        } */
        /* 搜索条件固化 end */

        const res = await this.$axiosApi.invoices(req)

        this.loading = false
        this.isFirstLoad = false
        if (res && res.code === 200) {
          this.tableData = res.data.data
          this.pagination.current = res.data.current_page
          this.pagination.total = res.data.total
          this.pagination.pageSize = res.data.per_page
        }
      } catch (error) {
        this.isFirstLoad = false
        this.loading = false
      }
    },
    async handleSizeChange(val) {
      if (this.loading) {
        return false
      }
      this.loading = true
      await this.getList({
        per_page: val,
        page: 1,
      })
      this.loading = false
      this.intoView()
    },
    async handleCurrentChange(val) {
      if (this.loading) {
        return false
      }
      this.loading = true
      await this.getList({
        per_page: this.pagination.pageSize,
        page: val,
      })
      this.loading = false
      this.intoView()
    },
    _isMobile() {
      if (process.browser) {
        let flag = navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
        )
        return flag
      } else {
        return false
      }
    },

    onDownload() {},

    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },

    async downloadInvoice(order_sn) {
      this.downloadOrderSn = order_sn
      try {
        let res = await this.$axiosApi.subscriptionInvoicesDetail(order_sn)
        if (res && res.data && res.data.order) {
          this.downloadData = res.data.order
          this.downloadUserData = res.data.user

          this.$nextTick(function () {
            if (this.$refs.downloadInvoice) {
              this.$refs.downloadInvoice.getPdf()
            }
          })
        }
        this.downloadOrderSn = null
      } catch (error) {
        this.downloadOrderSn = null
        console.log(error)
      }
    },
    getOrderType(type) {
      switch (type) {
        case 20:
          return this.$t('user_submitAi')
          break
        case 21:
          return this.$t('user_promote')
          break
        case 22:
          return this.$t('user_other')
          break
        case 23:
          return this.$t('user_advertisement')
          break
        case 24:
          return this.$t('user_updateAi')
          break
        case 25:
          return this.$t('user_submitGpt')
          break
        default:
          return this.$t('user_other')
      }
    },
    intoView() {
      const dom = document.querySelector('.tabs-box')
      if (dom) {
        const top = dom.offsetTop

        const targetScrollPosition = Math.max(top - 100, 0)

        let timer = setTimeout(() => {
          window.scrollTo({
            top: targetScrollPosition,
            behavior: 'auto',
          })

          this.$nextTick(() => {
            clearTimeout(timer)
          })
        })
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common-table.scss';
.user-payment {
  .tTable {
    .statu {
      display: inline-block;
      height: 20px;
      font-size: 13px;
      padding: 0 6px;
      line-height: 19px;
      border-radius: 3px;
      &.order-statu-unpaid {
        color: #979797;
        border: 1px solid #979797;
      }
      &.order-statu-paid {
        color: #7150e6;
        border: 1px solid #7150e6;
      }
      &.order-statu-refunded {
        color: #ff4d4f;
        border: 1px solid #ff4d4f;
      }
    }
  }

  .pagination {
    text-align: right;
    margin-top: 20px;
    ::v-deep .el-pagination {
      padding: 0;
      .el-pagination__jump {
        .el-input {
          margin-right: 0;
        }
      }
    }
  }
}
</style>